function [R,affected,insertid] = mysql(SQL);

global CG;

MYSQLEXE = which('mysql');
MYSQLEXE(end:end+2) = 'exe';

affected = 0; insertid = 0;

%FIGURE OUT QUERY TYPE
parse=strsep(deblank(SQL),' ',1);
if strcmp(upper(parse{1}),'INSERT'), % INSERT
  querytype=1;
  SQL=[SQL,'; SELECT LAST_INSERT_ID();'];  
elseif strcmp(upper(parse{1}),'UPDATE'), % UPDATE
   querytype=2;
else  % SELECT
   querytype=0; 
end

% CONSTRUCT MYSQL COMMAND LINE QUERY
cmd=[MYSQLEXE,' --host="',CG.Misc.Database.Server, ...
    '" --user=',CG.Misc.Database.User,' --password=',CG.Misc.Database.Password,...
    ' --port=3306',...
    ' --raw --column-names' ...
    ' --database=',CG.Misc.Database.DBName ...
    ' --exec="',SQL,'"'];
[W,S]=system(cmd);

if W,
   error(sprintf('Error running external mysql: %s for SQL: %s',S,SQL));
   return
end


% GO THROUGH DIFFERENT QUERY TYPES
Newline = char(10); Tab =char( 9);
switch querytype
  case {0,2}; % SELECT  & UPDATE
    if length(S) >1 % RESULT FOUND 
      % FIND THE RETURNED LABELS
      PosNL = find(S==Newline);
      LabelsS = S(1:PosNL(1)-1); DataS = S(PosNL(1)+1:end);
      PosTab = find(LabelsS==Tab);
      NFields = length(PosTab) + 1;
      Fields = strsep(LabelsS,Tab);
      
      RF = textscan(DataS,repmat('%s',[1,NFields]),'Delimiter','\t');
      
      StructFields = '';
      for i=1:NFields
        NumTest = str2num(RF{i}{1});
        if ~isempty(NumTest) && isnumeric(NumTest)
          RF{i} = cellfun(@str2num,RF{i},'UniformOutput',0);
        end
        NullPos = find(strcmp(RF{i},'NULL'));
        for j=1:length(NullPos) RF{i}{NullPos(j)} = []; end
        StructFields = [StructFields,'''',Fields{i},''', RF{',num2str(i),'},'];
      end
      StructCreator = ['R = struct(',StructFields(1:end-1),');'];
      eval(StructCreator);
    else % NO RESULTS FOUND 
      R = [];
    end
    
  case 1; % INSERT
    PosNL = find(S==Newline);
    LabelsS = S(1:PosNL(1)-1); DataS = S(PosNL(1)+1:end);
    R=1;   affected=1;  insertid=str2num(DataS);
    
end
